package data;

import java.sql.Connection;
import java.sql.SQLException;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.sql.DataSource;
import org.apache.log4j.Logger;

public abstract class ConnectionProvider {
	
	private static final Logger logger = Logger.getLogger(ConnectionProvider.class);
	private static final String CONNECTIONPROVIDER_INFO = "ConnectionProvider is error"; 
	private static final String CONNECTIONPROVIDER_NAMING = "ConnectionProvider is Naming 'java:/comp/env/jdbc/appDb' is not found in JNDI "; 
	private static final String JNDI_DB_REF = "java:/comp/env/jdbc/appDb";

	private static DataSource ds;
	
    static {
        try {
            ConnectionProvider.ds = (DataSource) 
            		new InitialContext().lookup(ConnectionProvider.JNDI_DB_REF);
        } catch (NamingException e) { 
        	logger.error(ConnectionProvider.CONNECTIONPROVIDER_NAMING + e.getMessage());
        }
    }

    public static Connection getConnection() {
    	Connection conn = null;
    	if (ConnectionProvider.ds != null) {
    		try {
				conn = ConnectionProvider.ds.getConnection();
			} catch (SQLException e) {
				logger.error(ConnectionProvider.CONNECTIONPROVIDER_INFO + e.getMessage());
			}
    	}
        return conn;
    }
}
